package com.baway.main


import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.baway.base.path.RouterPath
import com.baway.base.view.BaseActivity
import com.baway.common.event.CustomEvent
import com.baway.common.view.BaseMvvmActivity
import com.baway.main.adapter.MainPageAdapter
import com.baway.main.databinding.ActivityMainBinding
import com.baway.main.entity.NavTabItem
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener


/**
 * 业务：
 * 1.承载所有子模块
 * 2.权限校验
 * 3.版本升级
 * 4.消息提示
 *
 */
@Route(path = RouterPath.PATH_MAIN_PAGE)
@AndroidEntryPoint
class MainActivity : BaseMvvmActivity<ActivityMainBinding>() {

    private lateinit var mNavController: NavigationController

    private var fragments = arrayListOf<Fragment>()

    //定义需要哪些用户权限
    private val needUserPermission = arrayListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.ACCESS_FINE_LOCATION
    )

    //用户没有同意的权限
    private val unGrantPermission = arrayListOf<String>()

    private var hasUnGranted = false


    override fun getLayoutId(): Int = R.layout.activity_main

    override fun initViews() {

        //处理底部导航
        mNavController = mDataBinding.mainBottomNav.custom()
            .addItem(newTabItem("首页", R.drawable.tab_home_default, R.drawable.tab_home_checked))
            .addItem(newTabItem("服务", R.drawable.tab_server_default, R.drawable.tab_server_checked))
            .addItem(newTabItem("消息", R.drawable.tab_message_default, R.drawable.tab_message_checked))
            .addItem(newTabItem("公告", R.drawable.tab_notice_default, R.drawable.tab_notice_checked))
            .addItem(newTabItem("我的", R.drawable.tab_mine_default, R.drawable.tab_mine_checked))
            .build()


        //使用ARouter获取其他模块Fragment的实例，减少对其他模块直接依赖
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_HOME_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_SERVICE_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_MESSAGE_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_NOTICE_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_MINE_PAGE).navigation() as Fragment)

        //初始化ViewPager
        mDataBinding.mainViewPager.apply {
            adapter =  MainPageAdapter(supportFragmentManager, fragments, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
            offscreenPageLimit = 4 //设置离屏的Fragment缓存大小
        }

        //设置底部导航切换事件
        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener{
            override fun onSelected(index: Int, old: Int) {
                mDataBinding.mainViewPager.currentItem = index
                if (index == 2 || index == 3){
                    mNavController.setHasMessage(index, false)
                    mNavController.setMessageNumber(index, 0)
                }
            }

            override fun onRepeat(index: Int) {
                if (mDataBinding.mainViewPager.currentItem != index){
                    mDataBinding.mainViewPager.currentItem = index
                }
            }
        })

        //设置ViewPager切换监听
        mDataBinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                mNavController.setSelect(position)
            }

            override fun onPageScrollStateChanged(state: Int) { }

        })

        //自定发起权限授权
        mDataBinding.mainViewPager.postDelayed({
            autoRequestPermisstion()
        }, 3000)
    }


    /**
     * 处理其他业务发送过来的事件
     */
    override fun handEvent(event: CustomEvent) {
        when(event.type){
            //有新的消息
            100 -> {
                //设置公告提示
                mNavController.setHasMessage(2, true)
                mNavController.setMessageNumber(2, event.data as Int)
            }
            //有新公告
            101 -> {
                //设置公告提示

                mNavController.setHasMessage(3, true)
                mNavController.setMessageNumber(3, event.data as Int)
            }
        }
    }


    /**
     * 使用RxPermission发起用户权限授权
     */
    private fun autoRequestRxPermission(){


    }

    private fun autoRequestPermisstion(): Boolean{
        //判断系统版本，只有在6.0以后才需要动态授权
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //清理一下未授权的用户权限
            unGrantPermission.clear()

            //查找还未授权的用户权限
            needUserPermission.forEach {
                //检查当前权限是否被用户同意
                var permissionState = checkSelfPermission(it)
                if (permissionState == PackageManager.PERMISSION_DENIED){ //未授权
                    unGrantPermission.add(it)
                }
            }

            //发起授权
            if (unGrantPermission.size > 0){
                requestPermissions(unGrantPermission.toTypedArray(), 102)
                return false
            }
        }
        return true
    }

    /**
     * 权限授权返回
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 102 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermission.forEach {
                //判断用户取消的权限
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }
        }

        //弹窗告诉用户去设置中心的应用详情里设置
        if (hasUnGranted){
            AlertDialog.Builder(this@MainActivity).apply {
                setTitle("权限提示")
                setMessage("没有授权，请到应用详情中设置")
                setPositiveButton("去设置") { dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted = false
                    openSettingsAppDetail()
                }
                setNegativeButton("取消"){dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted = false
                }
            }.show()
        }

    }

    private fun openSettingsAppDetail(){
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this@MainActivity.startActivity(intent)
    }


    private fun newTabItem(title: String, defaultResId: Int, checkedResId: Int): BaseTabItem{
        var normalTabView = NavTabItem(this@MainActivity).apply {
            initTabData(
                title,
                defaultResId,
                checkedResId,
                R.color.main_bottom_default_color,
                R.color.main_bottom_check_color
            )
        }
        return normalTabView

    }




}